package com.huiminpay.transaction.controller;


import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.huiminpay.common.cache.util.AmountUtil;
import com.huiminpay.common.cache.util.EncryptUtil;
import com.huiminpay.common.cache.util.ParseURLPairUtil;
import com.huiminpay.paymentagent.api.conf.AliConfigParam;
import com.huiminpay.transaction.api.IPayChannelParamService;
import com.huiminpay.transaction.api.IPayOrderService;
import com.huiminpay.transaction.api.IPlatformChannelService;
import com.huiminpay.transaction.api.ITransactionService;
import com.huiminpay.transaction.dto.OrderResultDTO;
import com.huiminpay.transaction.dto.PayChannelParamDTO;
import com.huiminpay.transaction.dto.PayOrderDTO;
import com.huiminpay.transaction.vo.OrderConfirmVO;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Controller
@Slf4j
public class PayController {

    @Reference
    ITransactionService iTransactionService;

    @Reference
    IPayChannelParamService iPayChannelParamService;

    @Reference
    IPayOrderService iPayOrderService;


    @RequestMapping("/qr/{token}")
    public String entry(@PathVariable String token, HttpServletRequest request) throws Exception {
        //解析token 判断请求的来源
        String value = EncryptUtil.decodeUTF8StringBase64(token);
        PayOrderDTO payOrderDTO = JSON.parseObject(value, PayOrderDTO.class);

        log.info("{}", payOrderDTO);

        // 2. 判断当前请求是来自微信或者支付宝 （header中user-agent的值来判断）
        String userAgent = request.getHeader("User-Agent");
        if (userAgent != null && userAgent.contains("AlipayClient")) {
            // 支付宝支付
            // 3.请求转发  并且将参数转换为键值对  使用转发隐藏信息
            return "forward:/pay-page?"+ ParseURLPairUtil.parseURLPair(payOrderDTO);

        }


        // 3.请求转发  并且将参数转换为键值对  使用转发隐藏信息
        return "forward:/pay-page?"+ ParseURLPairUtil.parseURLPair(payOrderDTO);
    }


    @RequestMapping("/pay-page")
    public String payPage() {

        //通过free Maker 来实现代码和页面的拼接
        return "pay";
    }


    @ApiOperation("支付宝下单")
    @PostMapping("/createAliPayOrder")
    public void createAliPayOrder(OrderConfirmVO orderConfirmVO,
                                  HttpServletResponse response) throws Exception {

        //对象转换，vo-dto
        PayOrderDTO payOrderDTO = new PayOrderDTO();
        BeanUtils.copyProperties(orderConfirmVO,payOrderDTO);
        payOrderDTO.setStoreId(Long.valueOf(orderConfirmVO.getStoreId()));

        // 注意参数转换问题 订单金额 元转分
        String ta = AmountUtil.changeY2F(orderConfirmVO.getTotalAmount());
        payOrderDTO.setTotalAmount(Integer.valueOf(ta));


        //调用服务层 下单，保存订单，并且对接第三方支付通道
        String alipayHtml = iTransactionService.createAliPayOrder(payOrderDTO);

        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write(alipayHtml);
        response.getWriter().flush();
        response.getWriter().close();

    }

    @ApiOperation("支付宝异步通知")
    @RequestMapping("/alipay/notify")
    public void notifyUrl(HttpServletRequest request, HttpServletResponse response) throws AlipayApiException, IOException {

        System.out.println(123);
        //1.验证签名
        //获取支付宝请求参数
        Map<String, String[]> parameterMap = request.getParameterMap();
        Map<String, String> map = new HashMap<>();
        parameterMap.keySet().forEach(key -> map.put(key,parameterMap.get(key)[0]));

        //通过订单id查询到订单详情
        String out_trade_no = map.get("out_trade_no");
        OrderResultDTO orderResultDTO = iPayOrderService.queryByOutTradeNo(out_trade_no);
        //查询支付参数
        PayChannelParamDTO payChannelParamDTO =
                iPayChannelParamService.queryPayChannelParam(orderResultDTO.getAppId(),
                                                             orderResultDTO.getChannel(),
                                                             orderResultDTO.getPayChannel());
        String param = payChannelParamDTO.getParam();
        AliConfigParam aliConfigParam = JSON.parseObject(param, AliConfigParam.class);

        String publicKey = aliConfigParam.getAlipayPublicKey(),
               charset=aliConfigParam.getCharest(),
               signType = aliConfigParam.getSigntype();

        //验签
        boolean b = AlipaySignature.rsaCheckV1(map, publicKey, charset, signType);
        if (!b){
            response.getWriter().write("error");

        }

        //2.更新状态
        //支付宝状态转系统状态  //交易状态支付状态,0-订单生成,2-支付成功,3-业务处理完成 4-交易关闭
        String tradeState = null;
        String trade_status = map.get("trade_status");
        if ("TRADE_FINISHED".equals(trade_status)){
            tradeState = "3";
        }else if ("TRADE_SUCCESS".equals(trade_status)){
            tradeState = "2";
        }else if ("TRADE_CLOSED".equals(trade_status)){
            tradeState = "4";
        }

        OrderResultDTO orderResultDTO1 = new OrderResultDTO();
        orderResultDTO1.setOutTradeNo(out_trade_no);
        orderResultDTO1.setTradeState(tradeState);
        orderResultDTO1.setUpdateTime(LocalDateTime.now());

        iPayOrderService.updateTradeState(orderResultDTO1);



        //3.向支付宝写入success
        response.getWriter().write("success");
        response.getWriter().flush();
        response.getWriter().close();
    }

}
